package com.scisoft.scan.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class LoginDBHelper extends SQLiteOpenHelper {

    public static final String Parm_UserName = "username";
    public static final String Parm_Password = "password";
    public static final String Parm_Sequence = "sequence";
    public static final String Parm_Remember = "remember";
    public static final String Parm_LoginState =  "loginstate";
    public static final String Parm_Url =  "url";

    public LoginDBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, null, version);
    }

    //设置参数
    public void SetParm(String parmKey,String parmValue) {
        SQLiteDatabase db = getWritableDatabase();
        if (db.isOpen()) {
            try {
                String sql = String.format("update parm_info set parmValue = '%s' where parmKey = '%s' ", parmValue,parmKey);
                db.execSQL(sql);
            } catch (Exception e) {
                throw e;
            } finally {
                db.close();
            }
        }
    }

    //获取参数
    public String GetParm(String parmKey) {
        String parmValue= "";
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM parm_info where parmKey = ? ", new String[]{parmKey});
        while (cursor.moveToNext()) {
            parmValue = cursor.getString(cursor.getColumnIndex("parmValue"));
        }
        cursor.close();
        return parmValue;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //参数表
        db.execSQL("CREATE TABLE if not exists parm_info(parmKey VARCHAR(80) PRIMARY KEY,parmValue VARCHAR(120))");
        //查询记录
        Cursor cursor =  db.rawQuery("select * from parm_info",new String[]{});
        int rowCount = cursor.getCount();
        if (rowCount == 0) {
            //初始化参数
            String sql = String.format("insert into parm_info values ('username','%s')", "");
            db.execSQL(sql);
            sql = String.format("insert into parm_info values ('password','%s')", "");
            db.execSQL(sql);
            sql = String.format("insert into parm_info values ('sequence','%s')", "无");
            db.execSQL(sql);
            sql = String.format("insert into parm_info values ('remember','%s')", "0");
            db.execSQL(sql);
            sql = String.format("insert into parm_info values ('loginstate','%s')", "0");
            db.execSQL(sql);
            sql = String.format("insert into parm_info values ('url','%s')", "192.168.1.109:8080");
            db.execSQL(sql);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}
